package com.xiaozhengkeji.xiaozhengblog.services.bus;

import com.google.gson.Gson;
import com.xiaozhengkeji.xiaozhengblog.base.entitys.SystemUserEntity;
import com.xiaozhengkeji.xiaozhengblog.base.service.SystemUserEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service("UserServiceBus")
public class UserServiceBus {
    SystemUserEntityService systemUserEntityService;

    @Autowired
    public UserServiceBus(SystemUserEntityService systemUserEntityService) {
        this.systemUserEntityService = systemUserEntityService;
    }

    /**
     * 注册用户
     */
    public int register(String username, String emailBox, String password, String regIP) {
        SystemUserEntity systemUserEntity = new SystemUserEntity();
        List<String> per = new LinkedList<>();
        per.add("user:def");
        systemUserEntity.setPermission(new Gson().toJson(per));
        systemUserEntity.setUsername(username);
        systemUserEntity.setEmail(emailBox);
        systemUserEntity.setPassword(password);
        systemUserEntity.setRegisterIp(regIP);
        systemUserEntity.setEndLoginIp(regIP);
        systemUserEntity.setUserState(1);
        return systemUserEntityService.insert(systemUserEntity);
    }

    /**
     * 判断用户或者邮箱是否存在
     */
    public Boolean isUserNameOrEmailExist(String usernameOrEmail) {
        if (systemUserEntityService.queryByUsername(usernameOrEmail).size() > 0) {
            return true;
        } else return systemUserEntityService.queryByEmail(usernameOrEmail).size() > 0;
    }

    /**
     * 用户登录
     */
    public Boolean loginUser(String usernameOrEmail, String password) {
        SystemUserEntity systemUserEntity;
        if (systemUserEntityService.queryByUsername(usernameOrEmail).size() > 0) {
            systemUserEntity = systemUserEntityService.queryByUsername(usernameOrEmail).get(0);
        } else {
            systemUserEntity = systemUserEntityService.queryByEmail(usernameOrEmail).get(0);
        }
        if (systemUserEntity == null) return false;
        if (systemUserEntity.getUserState() != 1) {
            return false;
        }
        return systemUserEntity.getPassword().equals(password);
    }
}
